package com.mystudy.atomic.interger;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * TODO: 自定义的显示锁
 *
 * @author acy
 * @since 2019/06/04 17:25
 */
public class MyCompareAndSetLock {
	private final AtomicInteger value=new AtomicInteger(0);

	private Thread lockedThread;
	public void tryLock() throws GetLockException{
		boolean compareAndSet = value.compareAndSet(0, 1);
		if (!compareAndSet){
			throw new GetLockException("Get Lock failed");
		}else {
			lockedThread=Thread.currentThread();
		}
	}

	public void unLock(){
		if (0==value.get()){
			return;
		}
		if (lockedThread==Thread.currentThread()){
			boolean success=value.compareAndSet(1,0);
			if (!success){
				throw new GetLockException("release Lock fail");
			}
		}
	}
}
